<template>
  <!-- 直播管理 -->
  <a-spin class="live-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l search-box">
        <div>
          <span>站点：</span>
          <a-select
            allowClear
            style="width:160px;"
            showSearch
            :defaultActiveFirstOption="false"
            :filterOption="filterOption"
            @search="getAllStation($event)"
            @change="changeLocation"
            v-model="search.locationId"
            placeholder="请选择站点"
            class="filter-select"
          >
            <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>C端状态：</span>
          <a-select v-model="search.isVisible" @change="handleByQueryCond" style="width:160px;" placeholder="请选择C端状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">显示</a-select-option>
            <a-select-option value="0">隐藏</a-select-option>
          </a-select>
        </div>
      </div>
      <div class="r">
        <!-- <a-button type="primary" style="margin-right:10px;background:#1d6fe9" @click="addProductVisible = true">新增产品</a-button> -->
        <a-button type="primary" style="margin-right:10px;background:#1d6fe9" @click="dealLocationPath(1)">新增</a-button>
      </div>
      <div class="r">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body">
      <a-table :columns="tableColumns" :pagination="false" :data-source="dyLiveProductList" :scroll="{ x: 900, y: tableHeight }" rowKey="id">
        <!-- 操作按钮 -->
        <template slot="action" slot-scope="text, record">
          <a-button v-if="record.isVisible === 0" type="link" herf="javascript:;" size="small" @click="dealPath(1, record.id)">显示</a-button>
          <a-button v-if="record.isVisible === 1" type="link" herf="javascript:;" size="small" @click="dealPath(0, record.id)">隐藏</a-button>
          <a-button v-if="record.isVisible === 1" type="link" herf="javascript:;" size="small" @click="dealLocationPath(2, record)">编辑</a-button>
        </template>
      </a-table>
    </div>

    <a-modal v-model="addLocationVisible" :title="locationType === 1 ? '新增直播页面' : '编辑直播页面'" @ok="handleAddLocation" @cancel="addLocationClose">
      <a-form-model :model="addLocationForm" ref="addLocationForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-model-item label="站点" prop="locationId" :rules="[{ required: true, trigger: 'change', message: '请选择站点' }]">
          <a-select allowClear showSearch :defaultActiveFirstOption="false" :filterOption="filterOption" @change="selectLocation" v-model="addLocationForm.locationId" placeholder="请选择站点">
            <a-select-option v-for="item in allStation" :key="item.id" :cityName="item.city" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="页面路径" prop="path" :rules="[{ required: true, trigger: 'blur', message: '请填写页面路径' }]">
          <a-input allowClear :disabled="locationType !== 1" v-model="addLocationForm.path" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
  </a-spin>
</template>

<script>
import { getCommonApiSearch, livelocationAdd, livelocationUpdate, livelocationVisible, livelocationList, fixLiveProduct, topLiveProduct, addLiveProduct, fixLiveProductMoney } from '@/service'
import upload from '@/components/upload/upload'
import moment from 'moment'
import debounce from 'lodash/debounce'
import { getToken } from '@/util/method'
export default {
  name: 'dyLiveProductList',
  data() {
    // 节流
    this.getAllStation = debounce(this.getAllStation, 800)
    return {
      moment,
      headers: {
        Authorization: getToken()
      },
      addProductForm: {
        locationId: null,
        productId: null,
        pictureUrl: []
      },
      locationType: 1,
      //   排序弹窗状态
      sortingVisible: false,
      addLocationVisible: false,
      addLocationForm: {
        locationId: null,
        locationName: '',
        path: ''
      },
      sortForm: {
        id: null,
        sequence: null
      },
      //   佣金弹窗状态
      commissionVisible: false,
      commissionForm: {
        liveId: null,
        bigMoneyStr: null,
        secondMoney: null
      },
      // loading是否显示
      isLoading: false,
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // 全部站点
      allStation: [],
      // table数据查询条件
      search: {
        locationId: undefined, // 站点id
        productId: null, // 产品id
        productName: '' // 产品名称
      },
      // 订单列表
      dyLiveProductList: [],
      tableColumns: [
        { title: '站点ID', dataIndex: 'locationId' },
        { title: '站点名称', dataIndex: 'locationName' },
        { title: '页面路径', dataIndex: 'path' },
        { title: '操作', width: 200, dataIndex: 'action', scopedSlots: { customRender: 'action' } }
      ]
    }
  },

  components: {
    upload
  },

  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    selectLocation(e, option = {}) {
      const { data = {} } = option
      if (data && data.attrs && data.attrs.cityName) {
        this.addLocationForm.locationName = data.attrs.cityName
      } else {
        this.$messageSend.error('未知站点名')
      }
    },
    // 新增/编辑直播路径
    handleAddLocation() {
      this.$refs.addLocationForm.validate(async (valid) => {
        if (valid) {
          let res = null
          if (this.locationType === 1) {
            // add
            res = await livelocationAdd(this.addLocationForm)
          } else {
            // edit
            res = await livelocationUpdate(this.addLocationForm)
          }
          console.log(res)
          this.initQuery()
          this.addLocationVisible = false
          this.addLocationClose()
        } else {
          return false
        }
      })
    },
    addLocationClose() {
      this.addLocationForm = {
        locationId: null,
        locationName: '',
        path: '',
        id: ''
      }
      this.$refs.addLocationForm.resetFields()
    },
    // 显示与隐藏 type 0 -下架；1 - 上架
    dealPath(type = '', id = '') {
      const { $messageSend, initQuery } = this
      livelocationVisible({ isVisible: type, id })
        .then((res) => {
          initQuery()
          $messageSend.success('操作成功')
        })
        .catch((err) => err)
    },
    dealLocationPath(type = 1, row = {}) {
      this.addLocationVisible = true
      this.locationType = type
      if (type === 2) {
        const { id = '', locationId = '', locationName = '', path = '' } = row
        this.addLocationForm.id = id
        this.addLocationForm.locationId = locationId
        this.addLocationForm.locationName = locationName
        this.addLocationForm.path = path
      }
    },
    // 关闭新增弹窗
    addClose() {
      this.addProductForm = {
        locationId: null,
        productId: null,
        pictureUrl: []
      }
      this.getAllStation()
      this.$refs.addProductForm.resetFields()
    },
    // 打开修改弹窗
    handleOpenSort(id, sequence) {
      this.sortingVisible = true
      this.sortForm = { id, sequence }
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    getAllStation(e) {
      getCommonApiSearch({ keywords: e }).then((res) => {
        this.allStation = res
      })
    },
    // 选择了站点
    changeLocation() {
      this.initQuery()
    },
    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { locationId, isVisible } = this.search

      return {
        pageIndex,
        pageSize,
        locationId,
        isVisible
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, productId, productName } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          productId: productId || '',
          productName: productName || ''
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },
    /**
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      livelocationList(this.getParams())
        .then((rs) => {
          console.log(rs)
          this.dyLiveProductList = Object.freeze(rs.locationList) || []
          this.pagination.total = rs.total || 0
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    async showUp(id) {
      await fixLiveProduct({ id: id, isDelete: 0 })
      this.initQuery()
    },
    async showDown(id) {
      await fixLiveProduct({ id: id, isDelete: 1 })
      this.initQuery()
    },
    async showPlacedTop(id) {
      await topLiveProduct({ liveId: id })
      this.initQuery()
    }
  },

  mounted() {
    this.setSearch()

    // 获取所有站点
    getCommonApiSearch()
      .then((res = []) => {
        this.allStation = res
      })
      // 获取失败依然继续请求列表数据
      .catch((err) => err)

    this.initQuery()
  }
}
</script>

<style lang="less" scoped>
.live-review {
  padding: 16px;
}
// /deep/ .ant-upload-list-picture-card .ant-upload-list-item,
// /deep/ .ant-upload-list-picture-card-container {
//   width: 50px;
//   height: 50px;
//   margin: 0;
//   margin-right: 3px;
// }

.color-f55 {
  color: #f55f4e !important;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
.multi-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; // 超出两行则以...形式隐藏
  -webkit-box-orient: vertical;
}
.ztDis_box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.zt_discrible_btn {
  color: #0090ff;
  cursor: pointer;
}

.zt_discrible_solution_list {
  list-style: none;
}
</style>
